package com.by.service.house.impl;

import com.by.bean.house.House;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.exception.BusinessException;
import com.by.mapper.house.HouseMapper;
import com.by.service.house.HouseService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service
public class HouseServiceImpl extends BaseServiceImpl<House, HouseMapper> implements HouseService {

    /**
     * 新增房屋
     */
    public int save(House house) {
        //判断房间号是否存在
        List<String> name = baseMapper.queryBytName(house.getTname(), house.getUnit());
        //房间号为空
        if (name.isEmpty()) {
            return  baseMapper.insert(house);
        }
        //房间号不为空，遍历房间号
        for (int i = 0; i < name.size(); i++) {
            if (house.getHouseId().equals(name.get(i))) {
                throw new BusinessException("房间号已存在！");
            }
        }
        return  baseMapper.insert(house);
    }



    /**
     * 修改房屋
     */
    public int update(House house){
        //如果没修改房间号
        String name = baseMapper.queryById(house.getId());
        if (name.equals(house.getHouseId())) {
            return baseMapper.updateById(house);
        }
        //修改了房间号,判断房屋名是否相等
        List<String> nameList = baseMapper.queryBytName(house.getTname(), house.getUnit());
        //房间号为空 修改成功
        if (nameList.isEmpty()) {
            return baseMapper.updateById(house);
        }

        //遍历房间号
        for (int i = 0; i < nameList.size(); i++) {
            //如果房间号存在
            if (house.getHouseId().equals(nameList.get(i))) {
                throw new BusinessException("房间号已存在！");
            }
        }
        return baseMapper.updateById(house);
    }

    /**
     * 查询房屋详情
     */
    @Override
    public House get(Serializable id) {
        return baseMapper.get(id);
    }
}
